package com.jiawa.wiki.controller;


import com.jiawa.wiki.req.UserLoginReq;
import com.jiawa.wiki.req.UserQueryReq;
import com.jiawa.wiki.req.UserSaveReq;
import com.jiawa.wiki.resp.CommonResp;
import com.jiawa.wiki.resp.PageResp;
import com.jiawa.wiki.resp.UserLoginResp;
import com.jiawa.wiki.resp.UserQueryResp;
import com.jiawa.wiki.service.UserService;


import com.jiawa.wiki.utill.SnowFlake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {

    private final static Logger LOG = LoggerFactory.getLogger(UserController.class);
    @Resource
     private UserService userService;
    @Resource
    SnowFlake snowFlake;
    @Resource
    RedisTemplate redisTemplate;
    @GetMapping("/list")
    public CommonResp<PageResp> list (@Valid UserQueryReq req){
        CommonResp commonResp = new CommonResp();
        PageResp<UserQueryResp> list = userService.list(req);
        commonResp.setContent(list);
        return commonResp;
    }
    @PostMapping("/save")
    public CommonResp save( @Valid @RequestBody UserSaveReq req){
        req.setPassword(DigestUtils.md5DigestAsHex(req.getLoginName().getBytes()));
        CommonResp resp = new CommonResp<>();
        userService.save(req);
        return resp;
    }
    @DeleteMapping("/delete/{id}")
    public  CommonResp delete( @PathVariable Long id){
        CommonResp resp = new CommonResp<>();
        userService.delete(id);
        return resp;
    }
    @PostMapping("/resetPassword")
    public CommonResp resetPassword( @Valid @RequestBody UserSaveReq req){
        req.setPassword(DigestUtils.md5DigestAsHex(req.getLoginName().getBytes()));
        CommonResp resp = new CommonResp<>();
        userService.resetPassword(req);
        return resp;
    }
    @PostMapping("/login")
    public CommonResp login( @Valid @RequestBody UserLoginReq req){
        req.setPassword(DigestUtils.md5DigestAsHex(req.getLoginName().getBytes()));
        CommonResp resp = new CommonResp<>();
        UserLoginResp login = userService.login(req);
        Long Token = snowFlake.nextId();
        login.setToken(Token.toString());
        LOG.info("Token{}放入redis中",Token);
        redisTemplate.opsForValue().set(Token,login,3600*24, TimeUnit.SECONDS);


        resp.setContent(login);
        return resp;
    }
    @GetMapping("/logout/{token}")
    public  CommonResp delete( @PathVariable String  token){
        CommonResp resp = new CommonResp<>();
        redisTemplate.delete(token);
        return resp;
    }
}
